import React from "react";
import type { LazyExoticComponent, ComponentType } from "react";
import { Meta, type RouteObject, type ImportComponent } from "../types/route";
import ErrorBoundary from "../components/error/ErrorBoundary";
import ErrorPage from "../components/error/ErrorPage";
import { lazy } from "react";
import { Navigate } from "react-router-dom";

const withLazy = (
  importFn: () => ImportComponent,
  meta: Meta,
): React.ReactElement => {
  const Component = lazy(() =>
    importFn().then((module: ImportComponent) => ({ default: module.default })),
  ) as LazyExoticComponent<ComponentType<unknown>>;

  return (
    <ErrorBoundary
      fallback={({ error, onRetry }) => (
        <ErrorPage error={error} onRetry={onRetry} />
      )}
    >
      <Component {...meta} />
    </ErrorBoundary>
  );
};

export const routes: RouteObject[] = [
  {
    path: "/",
    element: <Navigate to="/index" replace />,
  },
  {
    path: "/index",
    element: withLazy(() => import("../pages/index/index"), {Meta:{title:"首页",requiresAuth:false}}),
    children: [
      {
        path: "",
        element: <Navigate to="home-visual-data" replace />,
      },
      {
        path: "shopping-list",
        element: withLazy(() => import("../pages/ShoppingList/ShoppingList"), {Meta:{title:"商品列表",requiresAuth:false}}),
      },
      {
        path: "order-form",
        element: withLazy(() => import("../pages/OrderForm/OrderForm"), {Meta:{title:"订单表单",requiresAuth:false}}),
      },
      {
        path: "home-visual-data",
        element: withLazy(() => import("../pages/HomeVisualData/HomeVisualData"), {Meta:{title:"首页可视化数据",requiresAuth:false}}),
      },
      {
        path: "data-visualization",
        element: withLazy(() => import("../pages/Datavisualization/Datavisualization"), {Meta:{title:"数据可视化",requiresAuth:false}}),
      },
      {
        path: "ai-data-analysis",
        element: withLazy(() => import("../pages/AIDataAnalysis/AIDataAnalysis"), {Meta:{title:"AI数据分析",requiresAuth:false}}),
      },
      {
        path: "add-shopping",
        element: withLazy(() => import("../pages/AddShopping/AddShopping"), {Meta:{title:"添加商品",requiresAuth:false}}),
      }
    ]
  },
  {
    path: "/about",
    element: withLazy(() => import("../views/about"), {Meta:{title:"关于",requiresAuth:false}}),
  },
  {
    path: "*",
    element: withLazy(() => import("../components/error/ErrorPage"), {
      title: "404页面",
      requiresAuth: false,
    }),
  },
];
